
#import "LLHttpTool.h"
#import <sys/utsname.h>

@implementation LLHttpTool

+ (void)get:(NSString *)url headParams:(NSDictionary *)headParams params:(NSDictionary *)params success:(void (^)(NSDictionary *result))success failure:(void (^)(NSString *error))failure {
    // 1.创建请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer = [self getHeadParamsFromParams:headParams];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript", nil];
    NSLog(@"url ：%@",url);
    [manager GET:url parameters:[self getNewParamsFromParams:params] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSNumber *number = responseObject[@"code"];
        if (number.integerValue == 0 ) {
            if (success) {
                success(responseObject);
            }
        }
        else {
            if (failure) {
                failure(responseObject[@"reason"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.localizedDescription);
        }
    }];
}

+ (void)post:(NSString *)url headParams:(NSDictionary *)headParams params:(NSDictionary *)params success:(void (^)(NSDictionary *result))success failure:(void (^)(NSString *msg))failure {
    // 1.创建请求管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer = [self getHeadParamsFromParams:headParams];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript",@"multipart/form-data",@"application/x-www-form-urlencoded", nil];
    NSLog(@"url ：%@",url);
    [manager POST:url parameters:[self getNewParamsFromParams:params] progress:^(NSProgress * _Nonnull uploadProgress) {
        //
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSNumber *number = responseObject[@"code"];
        if (number.integerValue == 0 || number.integerValue == 1009||number.integerValue == 1) {
            if (success) {
                success(responseObject);
            }else{
                if (failure) {
                    failure(responseObject[@"msg"]);
                }
            }
        }
        else {
            if (failure) {
                failure(responseObject[@"msg"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.localizedDescription);
        }
    }];
}

/// 上传多张图片
+ (void)uploadOperationToUrl:(NSString *)url
                      params:(NSDictionary *)params
                      files:(NSArray *)files
                      process:(void (^)(NSInteger writedBytes, NSInteger totalBytes))process
                      complete:(void (^)(BOOL successed, NSDictionary *result))complete
                      finish:(void (^)(void))finish {
    NSMutableArray *mutableOperations = [NSMutableArray array];
//    NSMutableArray *resultArr = [NSMutableArray array]; 
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    for (NSInteger i = 0; i < files.count; i++) {
        id fileItem = files[i];
        id value = fileItem;
        NSString *fileName = [NSString stringWithFormat:@"image%zd.png",i];
        NSString *key = @"image";
        NSString *mimeType = @"image/jpeg";
        if ([fileItem isKindOfClass:[NSDictionary class]]) {
            value = [fileItem objectForKey:@"file"];     // 支持四种数据类型：NSData、UIImage、NSURL、NSString
            key = [fileItem objectForKey:@"key"];        // 文件字段的key
            fileName = [fileItem objectForKey:@"name"];  // 文件名称
            mimeType = [fileItem objectForKey:@"type"];  // 文件类型
            mimeType = mimeType ? mimeType : @"image/jpeg";
        }
        
        NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:url parameters:[self getNewParamsFromParams:params] constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            if ([value isKindOfClass:[NSData class]]) {
                [formData appendPartWithFileData:value name:key fileName:fileName mimeType:mimeType];
            } else if ([value isKindOfClass:[UIImage class]]) {
                [formData appendPartWithFileData:UIImageJPEGRepresentation(value, 0.5) name:key fileName:fileName mimeType:mimeType];
            } else if ([value isKindOfClass:[NSURL class]]) {
                [formData appendPartWithFileURL:value name:key fileName:fileName mimeType:mimeType error:nil];
            } else if ([value isKindOfClass:[NSString class]]) {
                [formData appendPartWithFileURL:[NSURL URLWithString:value] name:key fileName:fileName mimeType:mimeType error:nil];
            }
        } error:nil];
        
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        
        NSURLSessionUploadTask *uploadTask;
        uploadTask = [manager
                      uploadTaskWithStreamedRequest:request
                      progress:^(NSProgress * _Nonnull uploadProgress) {
                          dispatch_async(dispatch_get_main_queue(), ^{
                          });
                      }
                      completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                          if (!error) {
                              if (complete) {
                                  complete(nil,responseObject);
                              }
                          }
                      }];
        
        [uploadTask resume];
        [mutableOperations addObject:uploadTask];
    }
    if (finish) {
        finish();
    }
}

/// 上传单张图片
+ (void)uploadImageWithUrl:(NSString *)url headParams:(NSDictionary *)headParams params:(NSDictionary *)params imageData:(NSData *)imageData fileName:(NSString *)fileName success:(void (^)(NSDictionary *result))success failure:(void (^)(NSString *msg))failure {
    // 创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.requestSerializer = [self getHeadParamsFromParams:headParams];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/javascript",@"multipart/form-data",@"multipart", nil];
    // 3.发送请求
    [manager POST:url parameters:[self getNewParamsFromParams:params] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFormData:imageData name:fileName];
        //            [formData appendPartWithFileData:imageData name:@"imageUrl" fileName:[NSString stringWithFormat:@"%@.png",fileName] mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSNumber *number = responseObject[@"code"];
        if (number.integerValue == 0 ) {
            if (success) {
                success(responseObject);
            }
        }
        else {
            if (failure) {
                failure(responseObject[@"msg"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error.localizedDescription);
        }
    }];
}

#pragma mark - 私有方法

// 加入公共参数放body
+ (NSDictionary *)getNewParamsFromParams:(NSDictionary *)params {
    NSMutableDictionary *newParams = [[NSMutableDictionary alloc] initWithDictionary:params];
    NSLog(@"%@",newParams);
    return newParams;
}
// 加入公共参数放head
+ (AFHTTPRequestSerializer *)getHeadParamsFromParams:(NSDictionary *)params {
    AFHTTPRequestSerializer *requestSerializer =  [AFJSONRequestSerializer serializer];
//    if(![[params allKeys] containsObject:@"longitude"]) {
//        [requestSerializer setValue:[LLUserDefaults objectForKey:LLLongitude] forHTTPHeaderField:@"longitude"];
//    } else {
//        if (![params[@"longitude"] isEqualToString:@"000"]) {
//            [requestSerializer setValue:params[@"longitude"] forHTTPHeaderField:@"longitude"];
//        }
//    }
//    if(![[params allKeys] containsObject:@"latitude"]) {
//        [requestSerializer setValue:[LLUserDefaults objectForKey:LLLatitude] forHTTPHeaderField:@"latitude"];
//    } else {
//        if (![params[@"latitude"] isEqualToString:@"000"]) {
//            [requestSerializer setValue:params[@"latitude"] forHTTPHeaderField:@"latitude"];
//        }
//    }
//    LLLoginModel *loginModel = [LLUserManager getLoginModel];
//    if(![[params allKeys] containsObject:@"authorization"]) {
//        [requestSerializer setValue:loginModel.accessToken forHTTPHeaderField:@"authorization"];
//    } else {
//        [requestSerializer setValue:params[@"authorization"] forHTTPHeaderField:@"authorization"];
//    }
//    [requestSerializer setValue:@"1.0" forHTTPHeaderField:@"version"];
    return requestSerializer;
}

+ (NSString *)deviceModelName {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    if ([deviceModel isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceModel isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,3"])    return @"iPhone 5c";
    if ([deviceModel isEqualToString:@"iPhone5,4"])    return @"iPhone 5c";
    if ([deviceModel isEqualToString:@"iPhone6,1"])    return @"iPhone 5s";
    if ([deviceModel isEqualToString:@"iPhone6,2"])    return @"iPhone 5s";
    if ([deviceModel isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceModel isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceModel isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceModel isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceModel isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    if ([deviceModel isEqualToString:@"iPhone9,1"])    return @"iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone9,3"])    return @"iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone10,1"])   return @"iPhone 8";
    if ([deviceModel isEqualToString:@"iPhone10,4"])   return @"iPhone 8";
    if ([deviceModel isEqualToString:@"iPhone10,2"])   return @"iPhone 8 Plus";
    if ([deviceModel isEqualToString:@"iPhone10,5"])   return @"iPhone 8 Plus";
    if ([deviceModel isEqualToString:@"iPhone10,3"])   return @"iPhoneX";
    if ([deviceModel isEqualToString:@"iPhone10,6"])   return @"iPhoneX";
    if ([deviceModel containsString:@"iPad"])          return @"iPad";
    
    return deviceModel;
}


+ (NSString *)deviceModelUUid{
    NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    return uuid;
}

//
//- (void)someViewController:(SomeViewController *)someViewController sendToAnotherVCWithName:(NSString *)name andIDNum:(NSString *)idNum {
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer.timeoutInterval = 20;
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
//    [manager POST:@"http://www.example.com/Project/upload.php" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        for (int i = 0; i < _photosArr.count; i++) {
//            UIImage *image = _photosArr[i];
//            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
//            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//            // 设置时间格式
//            [formatter setDateFormat:@"yyyyMMddHHmmss"];
//            NSString *dateString = [formatter stringFromDate:[NSDate date]];
//            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
//           
//            [formData appendPartWithFileData:imageData name:@"upload" fileName:fileName mimeType:@"image/jpeg"]; //
//        }
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        NSLog(@"---上传进度--- %@",uploadProgress);
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"```上传成功``` %@",responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"xxx上传失败xxx %@", error);
//    }];
//}


//比较两个时间大小
+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    
    NSComparisonResult result = [dateA compare:dateB];
    
    if (result == NSOrderedDescending) {
        //NSLog(@"oneDay比 anotherDay时间晚");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"oneDay比 anotherDay时间早");
        return -1;
    }
    //NSLog(@"两者时间是同一个时间");
    return 0;
    
}

// 字典转json字符串方法

+(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

@end
